package com.gitee.zjbqdzq;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RenameUtil {

    //    private static final String regex = "^(斗破苍穹)(\\d+)(.*)(\\.M4A)$";
    private static final String regex = "^(凡人修仙传) ?(第(\\d+)集) ?(.*)(\\.M4A)$";

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("D:/ximalay", "凡人修仙传");
        File file = path.toFile();
        String[] list = Objects.requireNonNull(file.list());
        for (String s : list) {
            String newName = rename(s, regex);
//            System.out.println(newName);
            Path oldPath = Paths.get(path.toString(), s);
            Path newPath = Paths.get(path.toString(), newName);
            if (oldPath.equals(newPath)) {
                continue;
            }
            Files.move(oldPath, newPath);
        }
    }

    private static String rename(String filename, String regex) {
        Pattern compile = Pattern.compile(regex);
        Matcher matcher = compile.matcher(filename);
        if (matcher.find()) {
            String num = matcher.group(3);
            int i = Integer.parseInt(num);
            String[] strings = {matcher.group(1), String.format("第%04d集", i), matcher.group(4) + matcher.group(5)};
            return String.join(" ", strings);
        }
        return filename;
    }
}
